import { create } from 'zustand'
import { iconMap, defaultIcon } from '@/utils/iconMap';

type DigitalEmployeeData = {
  [workflow: string]: {
    position: string[];
    grade: string[];  // 级别
    status: string[]; // 运行状态
    method: string[];
  };
};

type IconJson = {
  workflow: number;
  position: number;
  run_status: number; // 改成运行状态索引
};

type State = {
  digitalEmployeeData: DigitalEmployeeData;
  setDigitalEmployeeData: (data: DigitalEmployeeData) => void;
  getIconPath: (icon: string) => string | null;
};

// 本地存储 key
const STORAGE_KEY = 'digitalEmployeeData';

// 尝试从 localStorage 读取初始值
const loadFromLocalStorage = (): DigitalEmployeeData => {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : {};
  } catch {
    return {};
  }
};

export const useDigitalEmployeeStore = create<State>((set, get) => ({
  digitalEmployeeData: loadFromLocalStorage(),

  setDigitalEmployeeData: (data) => {
    set({ digitalEmployeeData: data });
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    } catch (e) {
      console.warn('保存到本地失败:', e);
    }
  },

  getIconPath: (icon: string) => {
    try {
      // 解析 icon JSON
      const { workflow, position, run_status } = JSON.parse(icon) as IconJson;
      const data = get().digitalEmployeeData;

      const workflowKeys = Object.keys(data);
      const workflowKey = workflowKeys[workflow];
      if (!workflowKey) return defaultIcon;

      const category = data[workflowKey];
      const positions = category?.position || [];
      const statusList = category?.status || [];

      const positionName = positions[position];
      const statusName = statusList[run_status];

      if (!positionName || !statusName) return defaultIcon;

      // --- 全局编号逻辑 ---
      let globalIndex = 0;
      for (let i = 0; i < workflow; i++) {
        const wKey = workflowKeys[i];
        if (!wKey) continue;
        const cat = data[wKey];
        globalIndex += cat.position?.length || 0;
      }

      const number = (globalIndex + position + 1).toString().padStart(2, "0");

      // 根据运行状态映射后缀
      let suffix: string;
      if (statusName === "在岗") {
        suffix = "s";
      } else if (statusName === "升级维护") {
        suffix = "e";
      } else {
        suffix = "w"; // 离岗、未部署等默认
      }

      const key = `${number}_${suffix}`;
      return iconMap[key] || defaultIcon;
    } catch (e) {
      console.error("Invalid icon JSON:", icon);
      return defaultIcon;
    }
  },
}));
